/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mware_lib;

import java.io.IOException;
import java.net.UnknownHostException;
import mware_lib.Communicator.Client;

/**
 * @author Gortex
 */
public class NameServiceProxy extends NameService {

    // IP und Port des originalobjekts
    private String ipAdresse;
    private int port;
    private ObjectBroker broker;

    public NameServiceProxy(String ip, int port, ObjectBroker broker) {
        this.ipAdresse = ip;
        this.port = port;
        this.broker = broker;
    }

    /**
     * Binden im Namensdienst und eintragen des Skeletons in das Referenzmodul
     * @param servant
     * @param name 
     */
    @Override
    public void rebind(Object servant, String name) {
        try {
            String ref = broker.manageReferences(servant, name);
            String message = "methodname:rebind;param1typ:String;param1value:" + ref + ";param2typ:String;param2value:" + name;
            Client sender = new Client(ipAdresse, port);
            sender.send(message);
            String reply = sender.receive();
            if (StringDecoder.hasException(reply)) {
                throw new MiddlewareException(StringDecoder.getReturnValue(reply));
            }
        } catch (IOException ex) {
            System.err.println("Skeleton ip: " + ipAdresse + ":" + port + " konnt nicht kontaktiert werden ");
        }
    }

    /**
     * Auflösen des Namens in die Objektreferenz
     * @param name
     * @return 
     */
    @Override
    public Object resolve(String name) {
        try {
            String message = "methodname:resolve;param1typ:String;param1value:" + name;
            Client sender = new Client(ipAdresse, port);
            sender.send(message);
            String reply = sender.receive();
            if (StringDecoder.hasException(reply)) {
                throw new MiddlewareException(StringDecoder.getReturnValue(reply));
            } else {
                String[] replyArray = reply.split(";");
                int beginIndex = replyArray[2].indexOf(':');
                return replyArray[2].substring(beginIndex + 1, replyArray[2].length());
            }
        } catch (UnknownHostException ex) {
            System.err.println("Skeleton ip: " + ipAdresse + ":" + port + " konnte nicht kontaktiert werden ");
            return null;
        } catch (IOException ex) {
            System.err.println("IO Exception aufgetreten in NameServiceProxy resolve");
            return null;
        }
    }
}
